package csc.nndp.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import csc.nndp.dao.User;
import csc.nndp.dao.UserDB;

/**
 * Servlet implementation class register
 */
//@WebServlet("/register")
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Register() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/register.jsp")
				.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		String message = null;
		if ((userName.length() < 5) || (userName.isEmpty())) {
			message = "User Name must > 5 characters and non emptys";
		} else if ((password.length() < 8) || (password.isEmpty())) {
			message = "Password must > 8 character and non empty";
		}else {

			// add new user
			User user = new User();
			user.setUserName(userName);
			user.setUserName(password);
			user.setFirstName(request.getParameter("firstName"));
			user.setLastName(request.getParameter("lastName"));
			user.setEmail(request.getParameter("email"));
			user.setRole(request.getParameter("role"));
			message= "Welcome to Page";
			try {
				UserDB.addUser(user);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		request.setAttribute("message", message);
		request.getRequestDispatcher("/success.jsp").forward(request,
				response);

	}
	
	
}
